package com.tools.service.impl;


import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.tools.commons.response.ResponseCode;
import com.tools.commons.utils.IdGenerator;
import com.tools.config.UploadProperties;
import com.tools.service.UploadStrategy;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;

@Service
@ConditionalOnProperty(value = "upload.strategy.type", havingValue = "s3")
@AllArgsConstructor
public class S3Strategy implements UploadStrategy {
    UploadProperties properties;
    AmazonS3 s3;

    @Override
    public String upload(InputStream inputStream) {
        String key = IdGenerator.uuid();
        uploadToS3(inputStream, key);
        return key;
    }

    private void uploadToS3(InputStream inputStream, String key) {
        try {
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentType("image/png");
            objectMetadata.setContentLength(inputStream.available());
            s3.putObject("cloud", key, inputStream, objectMetadata);
        } catch (IOException e) {
            e.printStackTrace();
            ResponseCode.BAD_REQUEST.throwException("服务器错误");
        }
    }

    @Override
    public String getType() {
        return properties.getType();
    }
}
